// pages/light/light.js
const windWidth = wx.getSystemInfoSync().windowWidth;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    windWidth: windWidth,
    weight: 8.2,
    // 开启自动称重
    checked: false,
    // websocket 
    socket: null,
    connected: false
  },

  onShow() {
    this.updateTabBarIndex();
  },

  // 自动称重开关
  onChange(e) {
    this.setData({
      checked: e.detail
    });

    // 开关是否打开
    if (this.data.checked) {
      this.wsConnect();
    } else {
      this.closeWebSocket();
    }
  },

  updateTabBarIndex() {
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 2
      })
    }
  },

  // 监听页面卸载
  onUnload() {
    this.closeWebSocket();
  },

  /* =====================
          Websocket
   ======================= */
  // 创建 ws 连接
  wsConnect() {
    const socket = wx.connectSocket({
      url: 'ws://localhost:49943/websocket',
      header: {
        'content-type': 'application/json'
      },
      success() {
        console.log("创建 webSocket 链接成功...");
      },
      fail(res) {
        console.log("创建 webSocket 失败", res);
      }
    })

    this.setData({
      socket: socket
    }, () => {
      console.log("连接状态:", this.getWebSocketState());
      this.data.socket.onOpen(() => {
        this.onWebSocketOpen();

        // 打开了就发送
        this.sendWebsocketMsg('Hello 后台 ! 我是微信小程序.');
      })
      this.data.socket.onMessage(event => {
        this.onWebSocketMessage(event);
      })
      this.data.socket.onClose(() => {
        this.onWebSocketClose();
      })
      this.data.socket.onError((error) => {
        console.log(error);
      })
    });
  },
  // 获取 websocket 连接状态
  getWebSocketState() {
    if (this.data.socket == null) {
      // undefind null
      return "websocket 还没有建立连接";
    }
    switch (this.data.socket.readyState) {
      case 0:
        return `[${this.data.socket.readyState}]正在连接中...`;
      case 1:
        return `[${this.data.socket.readyState}]已经连接并且可以通信...`;
      case 2:
        return `[${this.data.socket.readyState}]连接正在关闭...`;
      case 3:
        return `[${this.data.socket.readyState}]连接已经关闭或者打开连接失败...`;
      default:
        return `[-1]连接状态异常...`;
    }
  },

  // websocket 发送信息
  sendWebsocketMsg(msg) {
    if (this.data.socket.readyState === this.data.socket.OPEN) {
      console.log("Websocket 发送信息!");
      this.data.socket.send({
        data: msg
      });
    } else {
      console.log('WebSocket连接未建立!');
    }
  },

  // 监听 websocket 连接状态
  // websocket 关闭
  onWebSocketClose() {
    console.log('WebSocket连接已关闭');
  },
  // websocket 监听
  onWebSocketMessage(event) {
    console.log('接收到服务端发送的消息:', event.data);
  },

  // websocket 错误监听
  onWebSocketError() {
    console.log('WebSocket连接发生错误!');
    this.resetWsConnect();
  },

  // websocket 打开监听
  onWebSocketOpen() {
    console.log("WebSocket连接已打开!");
    this.setData({
      connected: true
    })
  },

  // 断开 ws 连接
  closeWebSocket() {
    /// 通过逻辑判断: 不采用 socket readyState [当然:最好是使用官方判断]
    if (this.data.socket && this.data.connected) {
      // 关闭WebSocket连接
      this.data.socket.close();
      this.resetWsConnect();
    }
  },

  // 打印 Websocket 连接状态
  printWsConnect() {
    console.log("连接状态: ", this.getWebSocketState());
  },

  // 重置 Websocket 连接状态
  resetWsConnect() {
    this.setData({
      // 切换开关 - 关闭
      checked: false,
      // 连接中断 - 断开
      connected: false
    });
  }
})